package com.katze.boot.applet.password.common;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.KeySpec;

/**
 * 综合采集-Redis加解密
 */
public class ICSRedisAESUtils {

    //	private final static String ALGORITHM = "AES/ECB/PKCS5Padding";
    private final static String ALGORITHM = "AES";
    private static String iv = "fedcba9876543210";
    private final static String KEY = "ics-2019";

    /**
     * Encrypt data
     *
     * @param secretKey
     *            - a secret key used for encryption
     * @param data
     *            - data to encrypt
     * @return Encrypted data
     * @throws Exception
     */
    public static String cipher(String secretKey, String data) throws Exception {

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), secretKey.getBytes(), 100000, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey key = new SecretKeySpec(tmp.getEncoded(), ALGORITHM);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, key);

        return toHex(cipher.doFinal(data.getBytes()));
    }


    public static String decipher(String data) throws Exception {
        return decipher(KEY,data);
    }

    public static String decipher(String secretKey, String data) throws Exception {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), secretKey.getBytes(), 100000, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey key = new SecretKeySpec(tmp.getEncoded(), ALGORITHM);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(toByte(data)));
    }

    public static String encrypt(String seed, String cleartext) {
        try {
            return cipher(seed, cleartext);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String seed, String encrypted) {
        try {
            return decipher(seed, encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * AES����
     */
    public static String encrypt2(String seed, String cleartext) {
        byte[] rawKey;
        try {
//			rawKey = getRawKey(seed.getBytes());
            byte[] result = encrypt(seed.getBytes(), cleartext.getBytes());
            return toHex(result);
            // return new String(Base64.encode(result, Base64.DEFAULT));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES����
     */
    public static String decrypt2(String seed, String encrypted) {
        try {
            byte[] rawKey;
            byte[] enc = toByte(encrypted);
            // byte[] enc = Base64.decode(encrypted, Base64.DEFAULT);
            byte[] result = decrypt(seed.getBytes(), enc);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);

        return decrypted;
    }

    public static String toHex(String txt) {
        return toHex(txt.getBytes());
    }

    public static String fromHex(String hex) {
        return new String(toByte(hex));
    }

    public static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
        return result;
    }

    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private final static String HEX = "0123456789ABCDEF";

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }
    public static String encrypt(String data){
        return encrypt(KEY,data);
    }
    public static String decrypt( String encrypted) {
        return decrypt(KEY,encrypted);
    }


//	public static String makeEncryptUrl(){
//		String username = "ff-pz";
//		String password = "Nh123123123";
//		String url = "monitor/capaoperate";
//		String callInfo = new Md5Hash(username+password+url).toString().toUpperCase();
//		String token = AESUtils.encrypt(username+"|"+password+"|"+callInfo);
//		String redirect = AESUtils.encrypt(url);
//		String  encryptUrl = "http://localhost:8089/ieop/security/sso?token="+token+"&redirect="+redirect;
//		System.out.println("���ܺ�url��"+encryptUrl);
//		return encryptUrl;
//	}



    public static void main(String[] args) throws Exception
    {
        String content = "eop#eop@1234";
        //String password = "eop-2016";
        String temp= ICSRedisAESUtils.encrypt(content);
        System.out.println("加密后：" + ICSRedisAESUtils.encrypt(content));
//        System.out.println("解密后：" + IcsRedisAESUtils.decrypt("8D769B23DFF8393D3F2060047865A92D"));
        System.out.println("解密后：" + ICSRedisAESUtils.decrypt("3A3B048436E88EAF39476EF8D0C348F2"));


        String result=null;
//		if("encrypt".equals(args[0])){
//			result = AESUtils.encrypt(args[1]);
//			System.out.println(result);
//		}
//		if("decrypt".equals(args[0])){
//			result = AESUtils.decrypt(args[1]);
//			System.out.println(result);
//		}
//		if(result==null){
//			System.out.println("请输入参数：encrypt|decrypt 参数：要（加密|解密）的值");
//		}
    }


}
